package com.test.login.serviceImpl;

import com.test.login.mapper.UserMapper;
import com.test.login.model.User;
import com.test.login.service.UserService;
import com.test.login.util.GenerateKey;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public User getById(String id) {
        User user = userMapper.selectByPrimaryKey(id);
        if (user == null) user = new User();
        return user;
    }

    @Override
    public int save(User user) {
        if (user.getId() == "" || user.getId() == null) {
            return this.add(user);
        } else {
            return this.update(user);
        }
    }

    @Override
    public List<User> list() {
        return userMapper.selectAll();
    }

    private int add(User user) {
        user.setId(GenerateKey.getKey(null, null));
        return userMapper.insert(user);
    }

    private int update(User user) {
        return userMapper.updateByPrimaryKey(user);
    }

}
